package com.hx.controller;

import com.hx.model.MessageBodyEntry;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.annotation.SubscribeMapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.security.Principal;

@Slf4j
@Controller
@RequestMapping("/")
public class MessageController {
    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;

    @GetMapping("/")
    public String index() {
        return "/index";
    }

    //接收前端send命令发送的
    @MessageMapping("/hello")
    @SendTo("/topic/hello2")
    public String hello(@Payload MessageBodyEntry chatMessage) {
        log.info("接收前端send命令发送的消息：{}", chatMessage);
        return "123";
    }

    //接收前端subscribe命令发送的
    @SubscribeMapping("/subscribe")
    @SendTo("/topic/hello2")
    public String subscribe() {
        return "客户端订阅成功——456";
    }

    //接收前端send命令，但是单对单返回
    @MessageMapping("/sayToTest")
    //@SendToUser("/queue/test")
    public String user(Principal principal, @Payload MessageBodyEntry chatMessage) {
        log.info("{}", principal);
        log.info("sayToTest={}", chatMessage);
        //可以手动发送，同样有queue
        simpMessagingTemplate.convertAndSendToUser("admin", "/queue/test", "ABC");
        return "111";
    }
}
